var PROJECT_NAME="/OASystem";
var provinces=[];

$(window).load(function() {
	//设置表单样式
	$(".cssform th").css({
		borderStyle:"solid",
		borderWidth:1,
		borderColor:$(".datagrid-toolbar").css("border-color"),
		background:$(".panel-header").css("background"),
		color:$(".panel-title").css("color"),
		fontWeight:'normal',
		fontSize:12,
		padding:'5px 0'
	});
	
	$(".cssform td").css({
		borderStyle:"solid",
		borderWidth:1,
		borderColor:$(".datagrid-toolbar").css("border-color"),
		background:$(".panel-body").css("background"),
		padding:5
	});
	
	$(".cssform input").css({
		background:'none',
		color:$(".panel-title").css("color"),
		width:'100%',
		border:0,
		fontSize:12
	});
	$(".txt").css({
		color:$(".panel-title").css("color")
	});
	$("#fm").form("enableValidation");
});
//用户登录
function userLogin() {
	//启用表单验证
    $("#loginFrm").form("enableValidation");
    var isValid = $("#loginFrm").form("validate");

    if (isValid) {
        $('#btnLogin').linkbutton('disable');
        //开始提交
        $.ajax({
            type: "post",
            url: "user_login.do",
            data: $("#loginFrm").serialize(),
            dataType: "json",
            beforeSend: function (xhr) {
                // 显示进度条
                $.messager.progress({
                    text: '正在登录中，请稍候...',
                    interval: 1000
                });
            },
            complete: function (xhr, textStatus) {
                $.messager.progress('close');
                $('#btnLogin').linkbutton('enable');
            },
            success: function (result) {
                if (result.success) {
                    $.messager.show({
                        title: '提示',
                        msg:result.message,
                        timeout: 3000,
                        showType: 'slide'
                    });
                    var $h1=$(window.frames["centerframe"].document).find("h1");
					$h1.animate({
						top:($("#centerframe").innerHeight()-$h1.height())/2
					},1000);
                    $("#loginWin").window("close");
                    $("#userInfo span").text("当前用户："+result.userName+"（"+result.userRole+"）   ");
                    $("#userInfo").fadeIn(500); 
                    loadMenu();
                    $("#loginUserName").val(result.userName);
                    $("#loginUserId").val(result.userId);
                    $("#loginRoleId").val(result.roleId);
                    
                } else {
                    $.messager.alert('提示', result.message, 'error', function () {
                        $('#btnLogin').linkbutton('enable');
                    });
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                $.messager.alert("提示", "连接服务器出错,请与系统管理员联系!", 'error');
            }
        });

    } else {
        return isValid;
    }
}
function loadMenu(){
	$("#mainmenu").tree({
    	url:"sys_getMenu.do",
    	animate:true,
    	lines:false,
		onLoadSuccess:function(node, data){
			$("#mainmenu *").css({
				transition:'all ease 0.5s 0s'
			});
			$(".tree-node + ul").css({
				transition:'none'
			});
		},
		onClick: function(node){
			if(!$("#mainmenu").tree("isLeaf", node.target)){
				var icons = $(node.target).find("span.tree-icon");
				if( $("#mainmenu").tree('getSelected').state=='closed'){
	                $("#mainmenu").tree('expand',node.target);
	                
	                if (icons) {
	                        $(icons[0]).addClass("icon-remove");
	                        $(icons[0]).removeClass("icon-add");
	                };
	                
	            }else if($("#mainmenu").tree('getSelected').state=='open'){
	            	 $("#mainmenu").tree('collapse',node.target);
	            	 if (icons) {
	                        $(icons[0]).addClass("icon-add");
	                        $(icons[0]).removeClass("icon-remove");
	                };
	            	 
	            }else{
	            	//没有分配子节点的操作
	            	alert('未分配子节点操作权限,请联系管理员!');
	            	return false;
	            }
			}else{
				$("#centerframe").attr("src",node.attributes);
			}
			return false;
		}
    });
}
$(function(){
	
	$("input").keypress(function(event){
		if(event.keyCode==13){
			userLogin();
		}
	});
	
	
	$("iframe").fadeIn(500);
	 //登录
	 $("#btnLogin").click(function () {
         userLogin();
     });

	//注册
     $("#btnReg").click(function () {
    	 $.messager.progress({
             text: '请稍候...',
             interval: 500
         });
    	//获取省列表
    		$.ajax({
    			url: PROJECT_NAME + '/province_list.do',
    			type: 'POST',
    			dataType: "json",
    			success: function(data, status) {
    				provinces=data;
    				var d=new Array();
    				d.push({ "text": "请选择","value": 0,"selected":true});
    				$.each(data,function(index,value){
    					d.push({ "text": value.name,"value": value.id});
    				});
    				//省列表
    				$('#province').combobox({
    					valueField: 'value',
    					textField: 'text',
    					data:d,
    					onChange:function(newValue, oldValue){
    						if (newValue>0) {
    							$.each(provinces, function(index, value) {
    								if (newValue==value.id) {
    									if (!value.cities) {
    										$.ajax({
    											url: PROJECT_NAME + '/city_list.do',
    											type: 'POST',
    											data:{provinceId:newValue},
    											dataType: "json",
    											success: function(data, status) {
    												value.cities=data;
    												var cd=new Array();
    												cd.push({ "text": "请选择","value": 0,"selected":true});
    												$.each(value.cities,function(i,v){
    													cd.push({ "text": v.name,"value": v.id});
    												});
    												$('#city').combobox('loadData',cd);
    											},
    											err: function(XMLHttpRequest, textStatus, err) {
    												$.messager.alert('错误', '对不起，获取城市列表失败！', 'error');
    											}
    										});
    									}else{
    										var cd=new Array();
    										cd.push({ "text": "请选择","value": 0,"selected":true});
    										$.each(value.cities,function(i,v){
    											cd.push({ "text": v.name,"value": v.id});
    										});
    										$('#city').combobox('loadData',cd);
    									}
    									
    									return false;
    								}
    							});
    						}else{
    							$('#city').combobox('loadData',[{ "text": "请选择","value": 0,"selected":true}]);
    						}
    					}
    				});
    				$.messager.progress('close');
    				$('#regdlg').dialog('open');
    			},
    			err: function(XMLHttpRequest, textStatus, err) {
    				$.messager.progress('close');
    				$.messager.alert('错误', '对不起，获取省市列表失败！', 'error');
    			}
    		});
    		$('#city').combobox({
    			valueField: 'value',
    			textField: 'text',
    			data: [{ "text": "请选择","value": 0,"selected":true}]
    		});
    	 $('#regdlg').dialog({
 			title: '注册用户',
 			height:275,
 			iconCls: 'icon-add',
 			onResize:function(width,height){
 				$("#regdlg .easyui-textbox,#regdlg .easyui-combobox,#regdlg .easyui-datebox").each(function(idx,dom){
 					$(this).textbox({    
 						width:$(this).parent().width()-15
 					});
 				});
 			},
 			buttons:[{
 				text:'确定',
 				iconCls: 'icon-ok',
 				handler:function(){
 					$('#fm').form('submit', {    
 					    url:PROJECT_NAME + '/user_saveorupdate.do',
 					    queryParams:{"action":"add"},
 					    onSubmit:function(para){
// 					    	if($("#dlguname").textbox("getValue").length==0){
// 					    		$.messager.alert('错误', '请输入用户名！', 'error');
// 					    		return false;
// 					    	}
// 					    	if($("#pwd").textbox("getValue").length==0){
// 					    		$.messager.alert('错误', '请输入密码！', 'error');
// 					    		return false;
// 					    	}
 					    	var valid=true;
 					    	if($("#pwd").textbox("getValue")!=$("#repwd").textbox("getValue")){
 					    		$.messager.alert('错误', '两次密码输入不一致！', 'error');
 					    		return false;
 					    	}
 					    	 $.messager.progress({
 				                text: '请稍候...',
 				                interval: 500
 				            });
 					    	 $.ajax({
 									url: PROJECT_NAME + '/user_exist.do',
 									type: 'POST',
 									async:false,
 									data:{
 										userName:$("#dlguname").textbox('getValue'),
 										userId:0
 									},
 									dataType: "json",
 									success: function(data, status) {
 										if(data=="1"){
 											valid=false;
 											$.messager.progress('close');
 											$.messager.alert('错误', '对不起，用户名已存在！', 'error');
 										}
 									},
 									err: function(XMLHttpRequest, textStatus, err) {
 										$.messager.progress('close');
 										$.messager.alert('错误', '对不起，验证用户名失败！', 'error');
 									}
 								});
 					    	 
 					    	 return valid && $('#fm').form("validate");
 					    },
 					    success:function(data){
 					    	$.messager.progress('close');
 					        if(parseInt(data)>0){
 					        	$('#regdlg').dialog('close');
 					        	showMsgBox("注册成功");
 					        }else{
 					        	$.messager.alert("错误", "操作失败！请与系统管理员联系!", 'error');
 					        }
 					    }    
 					});
 				}
 			},{
 				text:'关闭',
 				iconCls: 'icon-cancel',
 				handler:function(){
 					$('#regdlg').dialog('close');
 				}
 			}]
 		});
 		$("#dlgsex").combobox('select','保密');

 		$("#birthday").datebox('clear');
 		
 		$("#regdlg .easyui-textbox").textbox('clear');
 		
     });
     
     //验证session或cookies
	if($("#loginUserName").val()){
		$("#userInfo").fadeIn(500); 
		loadMenu();
	}else{
		$("#loginWin").window("open");
	}
});
function showMsgBox(msg){
	if(!$("#MsgPopWin").html()){
		$('<div id="MsgPopWin" style="border:1px solid #ccc;position:absolute;z-index: 9999;padding: 5px;background-color: white;display:none">	<img  src="img/yes-512x512.png" width="50" height="50" align="middle">	<span style="font:normal normal 16px 微软雅黑;position: relative;top: 5px;"></span></div>').appendTo($("body"));
	}
	$("#MsgPopWin span").text(msg);
	setCenter("#MsgPopWin");
		$("#MsgPopWin").delay(100).fadeIn("normal").delay(500).fadeOut("normal");
}
function setCenter(selector){
	var $e=$(selector);
	
	var page=getPageSize();
	var nDivLeft = page[2];
//alert(nDivLeft);
    // 整体宽度减去当前元素的宽度

          nDivLeft = nDivLeft - $e.outerWidth();

     // 计算中间位置

          nDivLeft = nDivLeft/2+$(document).scrollLeft();


          // 计算Top, 原理与上边的原理一致

          var nDivTop = page[3];
//alert(nDivTop);

          nDivTop = nDivTop - $e.outerHeight();

          nDivTop = nDivTop/2+$(document).scrollTop();

          $e.css({
          	top:nDivTop,
          	left:nDivLeft
          });
}
function getPageSize() {
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else {
        if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac    
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari    
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }
    }
    var windowWidth, windowHeight;
    if (self.innerHeight) { // all except Explorer    
        if (document.documentElement.clientWidth) {
            windowWidth = document.documentElement.clientWidth;
        } else {
            windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
    } else {
        if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode    
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else {
            if (document.body) { // other Explorers    
                windowWidth = document.body.clientWidth;
                windowHeight = document.body.clientHeight;
            }
        }
    }       
    // for small pages with total height less then height of the viewport    
    if (yScroll < windowHeight) {
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }    
    // for small pages with total width less then width of the viewport    
    if (xScroll < windowWidth) {
        pageWidth = xScroll;
    } else {
        pageWidth = windowWidth;
    }
    arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
    return arrayPageSize;
}